<?php
/*
 +----------------------------------------------------------------------
 + Title        : Alidayu 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2021/8/3 22:55
 + Last-time    : 2021/8/3 22:55+ chen2
 + Desc         : Alidayu
 +----------------------------------------------------------------------
*/


namespace randy\tools\units;


use aliyun\core\Config as AliyunConfig;
use aliyun\core\DefaultAcsClient;
use aliyun\core\profile\DefaultProfile;
use randy\exception\ApiException;

class Alidayu
{
    /**
     * 发送手机短信
     *
     * @access private
     *
     * @param string $mobile 手机号
     * @param array  $data   发送数据
     *
     * @return bool
     */
    public static function sendNotice(string $mobile, $code) : bool
    {
        $config = config('app.alidayu');
        $accessKeyId = $config['AccessKey'];    //参考本文档步骤2
        $accessKeySecret = $config['SecretKey'];//参考本文档步骤2
        // 加载区域结点配置
        AliyunConfig::load();

        // 短信API产品名
        $product = 'Dysmsapi';

        // 短信API产品域名
        $domain = 'dysmsapi.aliyuncs.com';

        // 暂时不支持多Region
        $region = 'cn-hangzhou';

        // 服务结点
        $endPointName = 'cn-hangzhou';

        // AccessKeyId
        $keyId = $accessKeyId;

        // AccessKeySecret
        $keySecret = $accessKeySecret;

        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $keyId, $keySecret);

        // 增加服务结点
        DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new \aliyun\SendSmsRequest();

        // 设置短信接收号码
        $request->setPhoneNumbers($mobile);

        // 设置签名名称
        $request->setSignName($config['SignName']);

        // 设置模板CODE
        $request->setTemplateCode($config['TemplateCode']);

        $data['code'] = $code;
        // 设置模板参数
        $request->setTemplateParam(json_encode($data));
        // 发起访问请求
        try {
            $client = new DefaultAcsClient($profile);
            $res = $client->getAcsResponse($request);
            if ($res['Code'] === 'OK') {
                return true;
            } else {
                throw new ApiException($res['Message']);
            }
        } catch (\exception $e) {
            throw $e;
        }
    }
}